package com.cat.slidingWindow;

import java.util.Arrays;
import java.util.HashMap;

/**
 * @author cat
 * @description https://leetcode.cn/problems/maximum-number-of-occurrences-of-a-substring/
 * @create 2025/7/27 19:32
 * @since JDK17
 */

public class Solution03 {
    static HashMap<String, Integer> map = new HashMap<>();
    static int[] h = new int[128];
    public int maxFreq(String str, int maxLetters, int minSize, int maxSize) {
        Arrays.fill(h, 0);
        // 长的字符串一定是包含短的,答案肯定是要取最短的字符串
        int total, ans = 0, n = str.length(), cnt = 0;
        for (int l = 0, r = 0; r < n; l++) {
            while (r < n && r - l < minSize) {  // 一直扩大
                cnt += h[str.charAt(r++)]++ == 0 ? 1 : 0;
            }
            if (cnt <= maxLetters) {    // 符合要求
                String s = str.substring(l, r);
                total = map.getOrDefault(s, 0) + 1;
                map.put(s, total);    //
                ans = Math.max(ans, total);
            }
            cnt -= h[str.charAt(l)]-- == 1 ? 1 : 0;
        }
        map.clear();
        return ans;
    }
}
